import { memo, useCallback, useState } from 'react';
import { TextField, IconButton } from '@mui/material'
import { Language } from '@mui/icons-material';
import PropsType from "prop-types";
import MuiLangEditDialog from './MuiLangEditDialog'

const MuiI18nTextFild = (props) => {

  const {placeholder, label, type, InputProps, variant, required, value, onChange, ...othersProps} = props
  const [openEditI18n, setOpenEditI18n] = useState(false)

  const onLocalChange = useCallback((event) => {
    onChange({
      defaultValue: event.target.value,
      i18nValue: value.i18nValue
    })
  }, [value])

  return (
    <div>
      <TextField value={value.defaultValue} required={required} onChange={onLocalChange} placeholder={placeholder} label={label} variant={variant} type={type} InputProps={{
        ...InputProps,
        endAdornment: (
          <IconButton onClick={() => setOpenEditI18n(true)}>
            <Language />
          </IconButton>
        )
      }} { ...othersProps }/>
      <MuiLangEditDialog
        required={required}
        open={openEditI18n}
        handleClose={() => setOpenEditI18n(false)}
        initialI18n={value}
        confirm={(values) => onChange(values)}
      ></MuiLangEditDialog>
    </div>
  )
}

MuiI18nTextFild.propTypes = {
  placeholder: PropsType.string,
  label: PropsType.string.isRequired,
  type: PropsType.string,
  variant: PropsType.string
}

MuiI18nTextFild.defaultProps = {
  placeholder: '',
  type: 'text',
  variant: 'filled'
}

export default memo(MuiI18nTextFild)